#include "standardagentfactory.h"

#include <QPluginLoader>
#include "defaultagent.h"
#include "log.h"
#include "../paths.h"

namespace Wishmaster {

StandardAgentFactory::StandardAgentFactory()
{

}

bool StandardAgentFactory::loadPluginsFromDirectory(const QString& pluginDirectory)
{
	bool found = false;
	log(llNormal, "Loading chanagents from directory: %s", qPrintable(pluginDirectory));
	QDir dir(pluginDirectory);
	foreach(const QString& filename, dir.entryList(QDir::Files))
	{
		log(llDebug, "Trying to load: %s", qPrintable(filename));
		QPluginLoader loader(dir.absoluteFilePath(filename));
		QObject* instance = loader.instance();
		if(instance)
		{
			ChanAgent* agent = qobject_cast<ChanAgent*>(instance);
			if(agent)
			{
				if(agentLoaded(agent->id()))
				{
					//delete agent;
					continue;
				}
				found = true;
				log(llNormal, "Loading agent: %s", qPrintable(agent->id()));
				m_agents.append(agent);
			}
			else
				log(llDebug, "!agent");
		}
		else
                        log(llDebug, "!instance: %s", qPrintable(loader.errorString()));
	}
	return found;
}

void StandardAgentFactory::loadPlugins()
{
	if(loadPluginsFromDirectory("./plugins/chanagents") ||
	   loadPluginsFromDirectory("../plugins/chanagents")) // Try to find plugins from build directory first
		return;

	if(!loadPluginsFromDirectory(DefaultPath::agentPlugins()))
	{
		log(llError, "Unable to find agent plugins");
	}
}

ChanAgent* StandardAgentFactory::makeAgent(const QString& id, const QString& host)
{
	foreach(ChanAgent* agent, m_agents)
	{
		if(agent->id() == id)
			return agent->clone(host);
	}
	return 0;
}

QStringList StandardAgentFactory::agentList()
{
	QStringList list;
	foreach(ChanAgent* agent, m_agents)
	{
		list.append(agent->id());
	}
	return list;
}

bool StandardAgentFactory::agentLoaded(const QString& id)
{
	foreach(ChanAgent* agent, m_agents)
	{
		if(agent->id() == id)
			return true;
	}
	return false;
}

} // namespace Wishmaster
